/**
 * 1,   状态 ：-1 禁用 0 离线，1 激活  ，2 负荷， 3 睡眠，4 断开   
 */
var xlsx = require("node-xlsx");
var fs = require("fs");

var _ljs=require("./mmlog").root("[sever/agent.js]");

var _session = require("./session");
var _util = require("./util");
var _config = require("./config");

var _socket = require("./socket");
var _WXapi = require("./channel/WeChat-API");

var _dbAgent = require("./db/agent");

var Agents = new Map();
var AgentArray = [];

function Agent(jobId) {

	this.jobId = jobId;
	this.status = 0;
	this.counts = 0;
	this.business = "all";

	this.change = function(val) {
		this.status = val;
		return val;
	};
	this.bs = function(val) {
		this.business = val;
		return val;
	};

	this.count = function(val) {
		this.counts += val;
		if(this.counts>=5){
			this.change(2);
		}else{
			this.change(1);
		}
		return this.counts;
	}
}

var _self = {

	/**
	 * 创建坐席账号
	 * 只有在安装界面时候才会有这个接口
	 * @param {Object} count
	 * @param {Object} cb 
	 */
	create: function(count, cb) {
		var data = [
			["序号", "账号", "密码", "业务类型", "状态","角色"]
		];
		var index = 10000;
		for (var i = 0; i < count; i++) {
			
			data.push([i + 1, index, _util.rColor(), "0", 0,i==0?'ADMIN':'AGENT']);
			index++;
		}
		var obj = [{
			name: "坐席账号",
			data: data
		}];
		var file = xlsx.build(obj);
		fs.writeFileSync("./output/agent.xlsx", file, "binary");
		_dbAgent.createAgents(data);
		var path = "output/agent.xlsx";
		cb(path);
	},

	accountConfig: function(data) {
		_ljs.debug("微信配置\n", data);
		fs.writeFileSync("output/wechat.json", JSON.stringify(data));
		_config.init();
		return data;
	},

	/**
	 * 坐席连接
	 * @param {Object} jobId
	 */
	connect: function(jobId) {
		var agent = new Agent(jobId);
		_ljs.debug("坐席连接:\n", agent);
		if (!Agents.has(jobId)) {
			Agents.set(jobId, agent);
			AgentArray.push(agent);
		}
		_ljs.debug("所有连接的坐席:\n", Agents.size);
		return _util.result(0);
	},

	/**
	 * 坐席会话数统计
	 */
	count: function(jobId,val) {
		Agents.get(jobId).count(val);
	},

	/**
	 * 坐席工作状态:激活
	 * @param {Object} jobId
	 */
	active: function(jobId,business) {
		_ljs.debug("坐席激活工作状态:", jobId);
		Agents.get(jobId).change(1);
		Agents.get(jobId).bs(business);
		_session.one(jobId,business);
		return _util.result(0);
	},

	/**
	 * 坐席工作状态:负荷
	 * @param {Object} jobId
	 */
	full: function(jobId) {
		_ljs.debug("坐席负荷工作状态:", jobId);
		Agents.get(jobId).change(2);
		return _util.result(0);
	},

	/**
	 * 坐席工作状态:休眠
	 * @param {Object} jobId
	 */
	sleep: function(jobId) {
		_ljs.debug("坐席睡眠工作状态:", jobId);
		Agents.get(jobId).change(3);
		return _util.result(0);
	},

	/**
	 * 坐席工作状态:断开
	 * @param {Object} jobId
	 */
	logout: function(jobId) {
		_ljs.debug("坐席断开工作状态:", jobId);
		Agents.get(jobId).change(4);
		_socket.del(jobId);
		return _util.result(0);
	},

	/**
	 * 会话推给坐席、选择最空闲坐席
	 * 当排序队列没有会话才执行
	 * @param {Object} session
	 */
	pushSession: function(session) {
		var a = _util.agentSort(AgentArray),
			_agent = null;
		for (var i = 0, size = a.length; i < size; i++) {
			if (a[i].status == 1 && a[i].business==session.business) {
				_agent = a[i];
				break
			}
		}
		if(!_agent){
			_ljs.info("当前没有激活的坐席、或者业务类型组坐席繁忙:",session.business);
			return false;
		}
		session.status = 1;
		session.jobId = _agent.jobId;
		_agent.count(1);
		_socket.session(_agent.jobId, session);
		session.startTime = new Date().getTime();
		return true;
	},

	query: function(type) {
		var data = {
			"total": AgentArray.length,
			"rows": AgentArray
		}
		return data;
	},


	/**
	 * 个人配置选项数据
	 * @param {Object} clientId
	 */
	config: function(clientId) {
		return {
			"total": 7,
			"rows": [{
				"name": "真实名称",
				"value": clientId,
				"group": "个人信息",
				"editor": "text",
				"id":"realname"
			}, {
				"name": "手机号码",
				"value": "",
				"group": "个人信息",
				"editor": "text",
				"id":"phone"
			}, {
				"name": "昵称",
				"value": clientId,
				"group": "个人信息",
				"editor": "text",
				"id":"nickname"
			}, {
				"name": "客服电话",
				"value": "",
				"group": "个人信息",
				"editor": "text",
				"id":"tel"
			}, {
				"name": "客服邮箱",
				"value": "",
				"group": "个人信息",
				"editor": {
					"type":"validatebox",
					"options":{
						"validType":"email"
					}
				},
				"id":"email"
			}, {
				"name": "自动接收会话",
				"value": "开启",
				"group": "会话设置",
				"editor": {
					"type": "checkbox",
					"options": {
						"on": "开启",
						"off": "关闭"
					}
				},
				"id":"isSession"
			}, {
				"name": "消息提示音",
				"value": "开启",
				"group": "会话设置",
				"editor": {
					"type": "checkbox",
					"options": {
						"on": "开启",
						"off": "关闭"
					}
				},
				"id":"isVoice"
			}]
		}
	}
}

_self.service={
	
	updateAgentInfo:function(jobId,param,callback){
		var _p=[param.key,param.value,jobId];
		_dbAgent.updateAgentInfo(_p,callback);
	}
	
}

module.exports = _self;